const express = require('express');
const router = express.Router();
const { Course, Category, User ,Chapter } = require('../../models');
const { Op } = require('sequelize');  //模糊匹配查询
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');
//列表查询 
router.get('/', async function(req, res, next) {
    try{
   
    //当前是第几页  
    const currentPage = Math.abs(Number(req.query.currentPage)) || 1;
    //每页显示多少条
    const pageSize = Math.abs(Number(req.query.pageSize))|| 10;
    //计算 offset
    const offset = (currentPage - 1) * pageSize; 

    const condition ={  //倒序
        ...getCondition(),
        order:[['id','desc']],
        limit: pageSize,
        offset
    } 
    const { query } = req
    if (query.categoryId) {
        condition.where = {
          categoryId: {
            [Op.eq]: query.categoryId
          }
        };
      }
      
      if (query.userId) {
        condition.where = {
          userId: {
            [Op.eq]: query.userId
          }
        };
      }
      
      if (query.name) {
        condition.where = {
          name: {
            [Op.like]: `%${ query.name }%`
          }
        };
      }
      
      if (query.recommended) {
        condition.where = {
          recommended: {
            // 需要转布尔值
            [Op.eq]: query.recommended === 'true'
          }
        };
      }
      
      if (query.introductory) {
        condition.where = {
          introductory: {
            [Op.eq]: query.introductory === 'true'
          }
        };
      }
      
    // const courses =await Course.findAll(condition)
    const {count ,rows} =await Course.findAndCountAll(condition)
    success(res,'success', {
        courses: rows,
        pagination: {
            total: count,
            currentPage,
            pageSize
        } 
    },200)
    }catch(err){
        failure(res,err)
    }
});
//新增
router.post('/', async function(req, res, next) {
    try{
        const body = filterBody(req.body)
        // 获取当前登录的用户 ID
        body.userId = req.user.id;

        const course = await Course.create(body)
        success(res,'success', course,201)
        }catch(err){
            failure(res,err)
        }
});
//id占位查询
router.get('/:id', async function(req, res, next) {
    try{
        const course = await getCourse(req)
        success(res,'success', course,201)
    }catch(err){
        failure(res,err)
    }
});
//删除课程
router.delete('/:id', async function(req, res, next) {
    try{
    const course = await getCourse(req)

    const count = await Chapter.count({ where: { courseId: req.params.id } });
    if (count > 0) {
      throw new Error('当前课程有章节，无法删除。');
    }
    await course.destroy()
        success(res,'success', {
            status: true,
            msg: '删除成功',
        },201)
    }catch(err){
        failure(res,err)
    }
})
//修改课程
router.put('/:id', async function(req, res, next) {
    try{
        const body = filterBody(req.body)
        const course = await getCourse(req)
        await course.update(body)
        success(res,'success', {
            status: true,
            msg: '更新成功',
            data:{course}
        },200)
    }catch(err){
        failure(res,err)
    }
})


const bodyFilter = ['categoryId','name','recommended','introductory','content','likesCount','image','chaptersCount']
function filterBody(body) {
    const result = {}
    bodyFilter.forEach(key => {
        if(body[key]){
            result[key] = body[key]
        }
    })
    return result
}
// 公共id 查询
async function getCourse(req) {
    const { id } = req.params;
    const condition = getCondition();
    const course = await Course.findByPk(id,condition)
    if( !course ) throw new NotFoundError(`ID:${id} 的课程不存在`)
    return course
}
// 关联模型数据 字段的筛选
function getCondition() {
    return {
      attributes: { exclude: ['CategoryId', 'UserId'] },
      include: [
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name']
        },
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar']
        }
      ],
    //   order:[['id','desc']],
    //   limit: pageSize,
    //   offset
    }
  }
module.exports = router;
